package com.dqhl.community.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.TextView;

import com.dqhl.community.R;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.OrderRecord;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.DoubleOperation;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.view.EvaluateSuccessDialog;
import com.dqhl.community.view.PictureHandlePopupWindow;
import com.dqhl.community.view.PictureSelectPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by Administrator on 2016/8/30.
 * 评价订单activity
 */
public class EvaluateActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mIvback;
    private TextView mTvTitle;
    private Button btnSubmit;
    private EvaluateSuccessDialog evaluateSuccessDialog;
    private ImageView iv_addPicOne;
    private ImageView iv_addPicTwo;
    private ImageView iv_addPicThree;
    private ImageView iv_addPicFour;
    private ImageView ivInsertPic;
    private ImageView mIvPic;//商品头像
    private TextView mTvName;//商品名称
    private TextView mTvPrice;//商品单价
    private PictureSelectPopupWindow pictureSelectPopupWindow; // 照片选择popupwindow
    private PictureHandlePopupWindow pictureHandlePopupWindow;
    private static int REQUESTCODE_PICTURE = 100;
    private static int REQUESTCODE_CAMERA = 101;
    private String namePicOne = "", namePicTwo = "", namePicThree = "", namePicFour = "";
    private int countPic = 0;// 添加图片数量  imageview处图片是否为空
    private int TAG = 0;//  标记是那张图片
    private String pic;
    private String name;
    private String price;
    private String orderId;
    private String orderName;
    private OrderRecord.Good goods;
    private TextView tv_total_number;
    private TextView tv_total_money;
    private TextView tv_order_name;
    private RatingBar rb_stars;
    private String score;
    private EditText et_content;
    private String content;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);

        initView();
        initData();

    }

    private void initData() {
        goods = (OrderRecord.Good) getIntent().getSerializableExtra("goods");
        Dlog.e(goods.toString());
        pic = goods.getGoods_pic();
        name = goods.getName();
        price = goods.getPrice_one();
        orderId = getIntent().getStringExtra("order_id");
        orderName = getIntent().getStringExtra("order_name");

        //初始赋值
        x.image().bind(mIvPic, Config.Api.base_img_url + pic);
        mTvName.setText(name);
        mTvPrice.setText("¥" + price);
        tv_total_number.setText(goods.getNumber());

        double price = Double.parseDouble(goods.getPrice_one());
        int number = Integer.parseInt(goods.getNumber());
        String total = String.valueOf(price * number);
        tv_total_money.setText(total);
        score = "5";
        tv_order_name.setText(orderName);
    }

    private void initView() {
        mIvback = (ImageView) findViewById(R.id.iv_top_back);
        mIvback.setVisibility(View.VISIBLE);
        mTvTitle = (TextView) findViewById(R.id.tv_top_title);
        mTvTitle.setText(R.string.txt_evaluate);
        btnSubmit = (Button) findViewById(R.id.btn_submit);
        iv_addPicOne = (ImageView) findViewById(R.id.iv_addPictureOne);
        iv_addPicTwo = (ImageView) findViewById(R.id.iv_addPictureTwo);
        iv_addPicThree = (ImageView) findViewById(R.id.iv_addPictureThree);
        iv_addPicFour = (ImageView) findViewById(R.id.iv_addPictureFour);
        ivInsertPic = (ImageView) findViewById(R.id.iv_insert_pic);
        mIvPic = (ImageView) findViewById(R.id.tv_pic);
        mTvName = (TextView) findViewById(R.id.tv_goods_name);
        mTvPrice = (TextView) findViewById(R.id.tv_goods_price);
        tv_total_number = (TextView) findViewById(R.id.tv_total_number);
        tv_total_money = (TextView) findViewById(R.id.tv_total_money);
        rb_stars = (RatingBar) findViewById(R.id.rb_stars);
        et_content = (EditText) findViewById(R.id.et_content);
        tv_order_name = (TextView) findViewById(R.id.tv_order_name);

        mIvback.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        iv_addPicOne.setOnClickListener(this);
        iv_addPicTwo.setOnClickListener(this);
        iv_addPicThree.setOnClickListener(this);
        iv_addPicFour.setOnClickListener(this);
        ivInsertPic.setOnClickListener(this);

        rb_stars.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                int starNums = ratingBar.getNumStars();
                switch (starNums) {
                    case 1:
                        score = "1";
                        break;
                    case 2:
                        score = "2";
                        break;
                    case 3:
                        score = "3";
                        break;
                    case 4:
                        score = "4";
                        break;
                    case 5:
                        score = "5";
                        break;
                }
            }
        });

        pictureSelectPopupWindow = new PictureSelectPopupWindow(this, pictureSelectItemsOnClick);
        pictureSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureSelectPopupWindow.backgroundAlpha(1.0f);
            }
        });
        pictureHandlePopupWindow = new PictureHandlePopupWindow(this, pictureHandleItemsOnClick);
        pictureHandlePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureHandlePopupWindow.backgroundAlpha(1.0f);
            }
        });
    }

    View.OnClickListener pictureSelectItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_take_photo:   // 调用系统相机
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(camera, REQUESTCODE_CAMERA);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_pick_photo:   // 调取手机相册
                    Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(picture, REQUESTCODE_PICTURE);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_cancel:   // 取消
                    pictureSelectPopupWindow.dismiss();
                    break;
            }
        }
    };

    View.OnClickListener pictureHandleItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_big_picture:
                    pictureHandlePopupWindow.dismiss();
                    Bundle bundle = new Bundle();
                    if (TAG == 1) {
                        bundle.putString("img_path", namePicOne);
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 2) {
                        bundle.putString("img_path", namePicTwo);
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 3) {
                        bundle.putString("img_path", namePicThree);
                        overlay(ImageShowerActivity.class, bundle);
                    } else if (TAG == 4) {
                        bundle.putString("img_path", namePicFour);
                        overlay(ImageShowerActivity.class, bundle);
                    }
                    break;
                case R.id.btn_delete: // 删除图片
                    pictureHandlePopupWindow.dismiss();
                    deleteImage();
                    break;
                case R.id.btn_cancel:
                    pictureHandlePopupWindow.dismiss();
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.btn_submit:
                doSubmit();
                break;
            case R.id.iv_insert_pic:
                if (countPic == 0) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_evaluate), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else if (countPic == 1) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_evaluate), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else if (countPic == 2) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_evaluate), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                } else if (countPic == 3) {
                    pictureSelectPopupWindow.showAtLocation(findViewById(R.id.activity_evaluate), Gravity.BOTTOM, 0, 0);
                    pictureSelectPopupWindow.backgroundAlpha(0.5f);
                }
                break;
            case R.id.iv_addPictureOne:
                TAG = 1;
                pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_evaluate), Gravity.BOTTOM, 0, 0);
                pictureHandlePopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.iv_addPictureTwo:
                TAG = 2;
                pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_evaluate), Gravity.BOTTOM, 0, 0);
                pictureHandlePopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.iv_addPictureThree:
                TAG = 3;
                pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_evaluate), Gravity.BOTTOM, 0, 0);
                pictureHandlePopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.iv_addPictureFour:
                TAG = 4;
                pictureHandlePopupWindow.showAtLocation(findViewById(R.id.activity_evaluate), Gravity.BOTTOM, 0, 0);
                pictureHandlePopupWindow.backgroundAlpha(0.5f);
                break;
        }
    }

    private void doSubmit() {
        content = et_content.getText().toString();
        File pic_a = new File(namePicOne);
        File pic_b = new File(namePicTwo);
        File pic_c = new File(namePicThree);
        File pic_d = new File(namePicFour);
        if (!pic_a.isFile()) {
            pic_a = null;
        }
        if (!pic_b.isFile()) {
            pic_b = null;
        }
        if (!pic_c.isFile()) {
            pic_c = null;
        }
        if (!pic_d.isFile()) {
            pic_d = null;
        }
        Dlog.e(user.getUserid() + ";" + user.getName() + ";" + goods.getGoods_id() + ";"
                + goods.getNumber() + ";" + goods.getName() + ";" + orderId + ";" + score + ";"
                + content + ";" + pic_a + ";" + pic_b + ";" + pic_c + ";" + pic_d);
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.Api.evaluate);
        params.addBodyParameter("userid", user.getUserid());
        params.addBodyParameter("user_name", user.getName());
        params.addBodyParameter("goods_id", goods.getGoods_id());
        params.addBodyParameter("goods_num", goods.getNumber());
        params.addBodyParameter("goods_name", goods.getName());
        params.addBodyParameter("order_id", orderId);
        params.addBodyParameter("score", score);
        params.addBodyParameter("content", content);
        params.addBodyParameter("pic_a", pic_a);
        params.addBodyParameter("pic_b", pic_b);
        params.addBodyParameter("pic_c", pic_c);
        params.addBodyParameter("pic_d", pic_d);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (0 == errCode) {
                    sendEvaluateSuccessBroadcast();
                    if (evaluateSuccessDialog == null) {
                        evaluateSuccessDialog = new EvaluateSuccessDialog(EvaluateActivity.this);
                    }
                    evaluateSuccessDialog.show();
                    evaluateSuccessDialog.setButtonClickListener(new EvaluateSuccessDialog.ImageViewClickListener() {
                        @Override
                        public void doCancel() {
                            evaluateSuccessDialog.dismiss();
                            finish();
                        }
                    });
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private void sendEvaluateSuccessBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_EVALUATE_SUCCESS);
        sendBroadcast(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == REQUESTCODE_PICTURE && resultCode == RESULT_OK) {
                Uri selectedImage = geturi(data);
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                if (c != null) {
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    String picturePath = c.getString(columnIndex);
                    Dlog.e("picturePath=========" + picturePath);
                    c.close();
                    addImages(picturePath);
//                    imgPath = picturePath;
//                    isNullPic = false;
//                    Dlog.e("imgPath:" + imgPath);
//                    x.image().bind(ivInsertPic, picturePath);
                }

            }
            if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK) {
                String sdState = Environment.getExternalStorageState();
                if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                    Dlog.e("sd card unmount");
                }
                String name = UUID.randomUUID().toString() + ".jpg";
                File file = new File("/sdcard/pintu");
                file.mkdirs();
                Bundle bundle = data.getExtras();
                //获取相机返回的数据，并转换为图片格式
                Bitmap bitmap = (Bitmap) bundle.get("data");
                FileOutputStream fout = null;
                String fileName = file.getPath() + name;
                try {
                    fout = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                    addImages(fileName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fout.flush();
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//                imgPath = fileName;
//                isNullPic = false;
//                Dlog.e("imgPath:" + imgPath);
//                x.image().bind(ivInsertPic, fileName);

            }
        }
    }

    public void addImages(String path) {
        if (countPic == 0) {
            if ("".equals(namePicOne) && namePicOne.length() == 0) {
                namePicOne = path;
                iv_addPicOne.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicOne, namePicOne);
                countPic += 1;
            }
        } else if (countPic == 1) {
            if ("".equals(namePicOne) && namePicOne.length() == 0) {
                namePicOne = path;
                iv_addPicOne.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicOne, namePicOne);
                countPic += 1;
            } else if ("".equals(namePicTwo) && namePicTwo.length() == 0) {
                namePicTwo = path;
                iv_addPicTwo.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicTwo, namePicTwo);
                countPic += 1;
            } else if ("".equals(namePicThree) && namePicThree.length() == 0) {
                namePicThree = path;
                iv_addPicThree.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicThree, namePicThree);
                ivInsertPic.setVisibility(View.GONE);
                countPic += 1;
            } else if ("".equals(namePicFour) && namePicFour.length() == 0) {
                namePicFour = path;
                iv_addPicFour.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicFour, namePicFour);
                countPic += 1;
                ivInsertPic.setVisibility(View.GONE);
            }
        } else if (countPic == 2) {
            if ("".equals(namePicOne) && namePicOne.length() == 0) {
                namePicOne = path;
                iv_addPicOne.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicOne, namePicOne);
                countPic += 1;
            } else if ("".equals(namePicTwo) && namePicTwo.length() == 0) {
                namePicTwo = path;
                iv_addPicTwo.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicTwo, namePicTwo);
                countPic += 1;
            } else if ("".equals(namePicThree) && namePicThree.length() == 0) {
                namePicThree = path;
                iv_addPicThree.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicThree, namePicThree);
                countPic += 1;
            } else if ("".equals(namePicFour) && namePicFour.length() == 0) {
                namePicFour = path;
                iv_addPicFour.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicFour, namePicFour);
                ivInsertPic.setVisibility(View.GONE);
                countPic += 1;
            }
        } else if (countPic == 3) {
            if ("".equals(namePicOne) && namePicOne.length() == 0) {
                namePicOne = path;
                iv_addPicOne.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicOne, namePicOne);
                ivInsertPic.setVisibility(View.GONE);
                countPic += 1;
            } else if ("".equals(namePicTwo) && namePicTwo.length() == 0) {
                namePicTwo = path;
                iv_addPicTwo.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicTwo, namePicTwo);
                ivInsertPic.setVisibility(View.GONE);
                countPic += 1;
            } else if ("".equals(namePicThree) && namePicThree.length() == 0) {
                namePicThree = path;
                iv_addPicThree.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicThree, namePicThree);
                ivInsertPic.setVisibility(View.GONE);
                countPic += 1;
            } else if ("".equals(namePicFour) && namePicFour.length() == 0) {
                namePicFour = path;
                iv_addPicFour.setVisibility(View.VISIBLE);
                x.image().bind(iv_addPicFour, namePicFour);
                countPic += 1;
                ivInsertPic.setVisibility(View.GONE);
            }
        }
    }

    //删除图片
    public void deleteImage() {
        if (TAG == 1) {
            namePicOne = "";
            iv_addPicOne.setVisibility(View.GONE);
            ivInsertPic.setVisibility(View.VISIBLE);
            ivInsertPic.setImageResource(R.drawable.ic_insert_picture);
            countPic -= 1;
        } else if (TAG == 2) {
            namePicTwo = "";
            iv_addPicTwo.setVisibility(View.GONE);
            ivInsertPic.setVisibility(View.VISIBLE);
            ivInsertPic.setImageResource(R.drawable.ic_insert_picture);
            countPic -= 1;
        } else if (TAG == 3) {
            namePicThree = "";
            iv_addPicThree.setVisibility(View.GONE);
            ivInsertPic.setVisibility(View.VISIBLE);
            ivInsertPic.setImageResource(R.drawable.ic_insert_picture);
            countPic -= 1;
        } else if (TAG == 4) {
            namePicFour = "";
            iv_addPicFour.setVisibility(View.GONE);
            ivInsertPic.setVisibility(View.VISIBLE);
            ivInsertPic.setImageResource(R.drawable.ic_insert_picture);
            countPic -= 1;
        }
    }

    /**
     * 解决小米部分手机调用系统相册失败
     *
     * @param intent
     * @return
     */
    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }
}
